package com.gitee.cui.petstore.actor;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 通用生产者类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/19 11:20
 **/
@Slf4j
public class Producer implements Runnable {

    /**
     * 生产者生产间隔时间
     */
    private static final int PRODUCE_GAP = 200;

    /**
     * 生产轮次
     */
    private static final AtomicInteger TURN = new AtomicInteger(0);

    /**
     * 生产者编号
     */
    private static final AtomicInteger PRODUCE_NO = new AtomicInteger(0);

    /**
     * 生产者名称
     */
    private String name;

    /**
     * 生产的动作
     */
    private Callable<?> action;

    private int gap = PRODUCE_GAP;

    public Producer(Callable<?> action, int gap) {
        this.action = action;
        this.gap = gap;
        this.name = "生产者-" + PRODUCE_NO.incrementAndGet();
    }

    @Override
    public void run() {
        while (true) {
            try {
                Object result = action.call();
                if (result != null) {
                    log.info("第{}轮生产：{}", TURN.get(), result);
                }
                ThreadUtil.sleepMilliSeconds(gap);

                TURN.incrementAndGet();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
